package edu.ynu.se.xiecheng.achitectureclass.soildata.controller;

import edu.ynu.se.xiecheng.achitectureclass.device.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.device.service.DeviceService;
import edu.ynu.se.xiecheng.achitectureclass.soildata.service.SensorDataService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.apache.shiro.authz.annotation.RequiresAuthentication;

import java.time.LocalDateTime;
import java.util.Map;

@Tag(name = "传感器数据", description = "传感器数据查询接口")
@RestController
@RequestMapping("/api/sensor-data")
@CrossOrigin(originPatterns = "*", allowCredentials = "true")
@RequiresAuthentication
public class SensorDataController {

    @Autowired
    private SensorDataService sensorDataService;
    
    @Autowired
    private DeviceService deviceService;

    @Operation(summary = "获取设备数据")
    @GetMapping("/{deviceNumber}")
    public ResponseEntity<?> getSensorData(
            @PathVariable String deviceNumber,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        try {
            Device device = deviceService.getDeviceByNumber(deviceNumber);
            if (device == null) {
                return ResponseEntity.badRequest()
                        .body(Map.of(
                                "success", false,
                                "message", "设备不存在"
                        ));
            }
            
            return ResponseEntity.ok(sensorDataService.getSensorData(device, startTime, endTime));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(Map.of(
                            "success", false,
                            "message", "获取数据失败: " + e.getMessage()
                    ));
        }
    }

    @Operation(summary = "获取大棚所有设备的最新数据")
    @GetMapping("/greenhouse/{greenhouseNumber}/latest")
    public ResponseEntity<?> getLatestData(@PathVariable String greenhouseNumber) {
        try {
            return ResponseEntity.ok(sensorDataService.getLatestData(greenhouseNumber));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(Map.of(
                            "success", false,
                            "message", "获取数据失败: " + e.getMessage()
                    ));
        }
    }
} 